package cn.edu.scut.sys.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.sql.JoinType;
import org.springframework.stereotype.Component;

import cn.edu.scut.sys.dao.LeaderDao;
import cn.edu.scut.sys.utils.StringUtils;
import cn.edu.scut.sys.vo.Leader;
import cn.edu.scut.sys.vo.TrainItem;

@Component("leaderDao")
public class LeaderDaoImpl implements LeaderDao{

	private SessionFactory sessionFactory;

	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Long count() {
		String hql = "select count(id) from Leader";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return Long.valueOf(query.uniqueResult().toString());
	}

	@Override
	public List<Leader> list(int start, int limit, String sort, String sidx) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Leader.class);
		criteria.createAlias("user", "user", JoinType.LEFT_OUTER_JOIN);
		criteria.setFirstResult(start).setMaxResults(limit);
		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(sidx)){
			if ("desc".equals(sort)){
				criteria.addOrder(Order.desc(sidx));
			} else if ("asc".equals(sort)){
				criteria.addOrder(Order.asc(sidx));
			}
		}
		
		return criteria.list(); 
	}

	@Override
	public void insert(Leader leader) {
		sessionFactory.getCurrentSession().save(leader);
		sessionFactory.getCurrentSession().flush();
		sessionFactory.getCurrentSession().clear();
	}

	@Override
	public Leader get(Long id) {
		return (Leader)sessionFactory.getCurrentSession().load(Leader.class, id);
	}

	@Override
	public void update(Leader leader) {
		sessionFactory.getCurrentSession().update(leader);
		sessionFactory.getCurrentSession().flush();
		sessionFactory.getCurrentSession().clear();
	}
	
	@Override
public List<Leader> getAll() {
		
		String hql = "from Leader";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		
		return query.list();
	}
	
}
